package so.sao.code.service.web.api;

import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import so.sao.code.dto.response.TagCodeDto;
import so.sao.code.service.infrastructure.enums.CodeMessage;
import so.sao.tag.core.TagCode;
import so.sao.tag.decryptor.TagDecryptor;
import so.sao.top.core.util.rest.RestException;

@Api(tags = "CodeCryptoClient", description = "标签解密接口")
@RestController
@RequestMapping("api/codecrypto")
public class CodeCryptoFeignController {

	@Autowired
	private TagDecryptor tagDecryptor;

	/**
	 * 内部服务间标签解密接口
	 * 
	 * @param subDomain
	 * @param codeStr
	 * @return
	 */
	@ApiOperation(value = "标签解密接口", notes = "根据子域名及加密串进行标签解密")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "subDomain", value = "标签子域名", required = true, dataType = "String", paramType = "body"),
			@ApiImplicitParam(name = "codeStr", value = "标签加密串", required = true, dataType = "String", paramType = "body") })
	@PostMapping(value = "decode", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public TagCodeDto tagDecodec(@NotBlank String subDomain, @NotBlank String codeStr) {
		TagCode tagCode = null;
		try {
			tagCode = tagDecryptor.decode(subDomain, codeStr);
		} catch (Exception e) {
			throw new RestException(HttpStatus.BAD_REQUEST, CodeMessage.IllegalCode, subDomain + "/" + codeStr);
		}
		if (tagCode == null) {
			throw new RestException(HttpStatus.BAD_REQUEST, CodeMessage.IllegalCode, subDomain + "/" + codeStr);
		}

		return new TagCodeDto(subDomain, tagCode.getSeqNum());
	}
}
